package com.atguigu.guli.service.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.guli.service.oss.utils.OssProperties;
import com.atguigu.guli.service.oss.service.FileService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private OssProperties ossProperties;

    @PostConstruct // java提供的 标注的方法在构造器调用后执行一次
    public void init() {
        this.endpoint = ossProperties.getEndpoint();
        this.accessKeyId = ossProperties.getAccessKeyId();
        this.accessKeySecret = ossProperties.getAccessKeySecret();
        this.bucketName = ossProperties.getBucketName();
    }

    String endpoint;
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    String accessKeyId;
    String accessKeySecret;
    String bucketName;

    @Override
    public String upload(MultipartFile file, String module) {
        try {
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            String fileName = file.getOriginalFilename();
            InputStream inputStream = file.getInputStream();
            //System.out.println("module = " + module);
            String filePath = module + new DateTime().toString("/yyyy/MM/dd/") + UUID.randomUUID().toString().replace("-", "") + fileName.substring(fileName.lastIndexOf("."));
            ossClient.putObject(bucketName, filePath, inputStream);

            ossClient.shutdown();
            String imgUrl = "https://" + bucketName + ".oss-cn-shanghai.aliyuncs.com/" + filePath;
            return imgUrl;
        } catch (Exception e) {
            // 将编译时异常转为运行时的异常抛出  由异常处理器处理给用户错误的响应
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteFile(String path, String module) {
        String objectName = path.substring(path.lastIndexOf(module));
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.deleteObject(bucketName, objectName);
        ossClient.shutdown();
    }

}
